<script setup="">
import {onMounted, ref, defineEmits} from "vue"
import {Plus} from "@element-plus/icons-vue"
import {adminPostBanner, adminPostTweet, adminUpdateBanner, adminUpdateTweet} from "@/request/mid_interface.js";
import {ElMessage} from "element-plus";
import axios from "axios";
import {Close} from "@element-plus/icons-vue"

const props = defineProps({
  param: {
    type: Object,
    required: false,
  }
})

const emit = defineEmits(["refresh", "close"]);

onMounted(() => {
  if (!props.param || !props.param.banner_id) {
  } else {
    const {
      banner_id,
      img,
      weburl,
      is_sticky,
    } = props.param
    bannerID.value = banner_id
    jumpUrl.value = weburl
    imageUrl.value = img
    isSticky.value = is_sticky ? "是" : "否"
  }
})

async function confirmSend() {
  if (!bannerID.value) {
    // 新建发布
    const postParam = {
      // "banner_id": "",
      "img": "",
      "weburl": "",
      "is_weburl": "",
      "is_sticky": "",
    }
    postParam.weburl = jumpUrl.value
    postParam.img = imageUrl.value
    postParam.is_sticky = isSticky.value === "是"
    postParam.is_weburl = jumpUrl.value.trim().length !== 0
    const res = await adminPostBanner(postParam)
    if (res.code) {
      ElMessage.success("发布成功！")
      emit('refresh')
    }
  } else {
    // 新建发布
    const postParam = {
      "banner_id": "",
      "img": "",
      "weburl": "",
      "is_weburl": "",
      "is_sticky": "",
    }
    postParam.banner_id = bannerID.value
    postParam.img = imageUrl.value
    postParam.weburl = jumpUrl.value
    postParam.is_weburl = jumpUrl.value.trim() === ""
    postParam.is_sticky = isSticky.value === "是"
    const res = await adminUpdateBanner(postParam)
    if (res.code) {
      ElMessage.success("编辑成功！")
      emit('refresh')
    } else {
      ElMessage.warning("请将信息填写完整")
    }
  }
}

const fileInput = ref(null)

function uploadImg(e) {
  let formData = new FormData()
  // 在这里写代码，判断文件是否为图片且大小小于2MB
  let file = e.target.files[0]
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.warning("需上传图片文件，且图片大小小于2MB")
    return
  }
  formData.append('file', e.target.files[0])
  axios.post('/api/img/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'token': localStorage.token,
    }
  }).then(res => {
    imageUrl.value = res.data.data
    console.log(res.data.data)
  }).catch(error => {
    console.log(error)
  })
}

function uploadImgBtn() {
  fileInput.value.click()
}

const stickyOptions = [
  {
    value: '是',
    label: '是',
  },
  {
    value: '否',
    label: '否',
  },
]

const bannerID = ref(0)
const jumpUrl = ref("")
const imageUrl = ref("")
const isSticky = ref("")

</script>

<template>
  <div class=" px-24 py-8">
    <input type="file" accept="image/*" ref="fileInput" style="display: none" @change="uploadImg">

    <!-- 跳转链接 -->
    <div class="flex items-center">
      <div class="w-28">跳转链接</div>
      <el-input
          v-model="jumpUrl"
          placeholder="留空时表示不跳转"
          class=""
          size="large"
      >
      </el-input>
    </div>

    <!-- 请上传图片 -->
    <div class="flex items-center mt-6">
      <div style="width: 94px">请上传图片</div>
      <div class="relative" v-if="imageUrl">
        <el-image
            class="rounded"
            style="width: 256px;height: 129px;"
            :src="imageUrl"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[imageUrl]"
            :initial-index="4"
            fit="cover"
        />
        <div @click="imageUrl=''" class="cursor-pointer absolute right-1 top-1 w-5 h-5 flex justify-center items-center"
             style="background: rgba(0,0,0,0.3)">
          <el-icon color="white">
            <Close/>
          </el-icon>
        </div>
      </div>
      <div @click="uploadImgBtn" v-if="!imageUrl"
           style="width: 256px;height: 129px;"
           class="cursor-pointer flex justify-center items-center bg-gray-100 rounded">
        <el-icon class="" style="">
          <Plus/>
        </el-icon>
      </div>
    </div>
    <div class="ml-24 mt-3 text-sm text-gray-400">*图片的尺寸为388*768</div>

    <!-- 是否置顶 -->
    <div class="flex items-center mt-6">
      <div style="width: 94px">是否置顶</div>
      <el-select
          v-model="isSticky"
          class="m-2 flex-1"
          placeholder="请选择是否置顶"
          size="large"
      >
        <el-option
            v-for="item in stickyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </div>

    <div class="flex justify-center mt-16">
      <div @click="emit('close')"
           class="cursor-pointer select-none hover:opacity-70 px-5 py-2 border rounded font-bold">取消
      </div>
      <div @click="confirmSend"
           class="cursor-pointer select-none hover:opacity-70 px-5 py-2 border rounded font-bold ml-3 text-white"
           style="background: var(--themeColor); border: var(--themeColor);">确认保存
      </div>
    </div>

  </div>
</template>

<style scoped>
* {
  --el-pagination-hover-color: var(--themeColor);
  --el-input-focus-border-color: var(--themeColor);
}

/deep/ .el-dialog {
  border-radius: 20px;
}

/deep/ .m-2 {
  margin: 0;
}

/deep/ .el-input__wrapper {
  box-shadow: 0 0 0 1px #eee inset;
}

/deep/ .el-select__wrapper {
  box-shadow: 0 0 0 1px #eee inset;
}

/deep/ .el-input-group__append {
  transform: translateX(-1px);
  box-shadow: 0 0 0 1px #eee inset;
}
</style>
